<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd()">新增</a-button>
      </template>
      <template #cronLabel="{ text, record }">
        <EasyCronLabel :value="text" :disabled="record.enabled == 1 && hasPermission('rpa:flow:edit')" @change="(cron)=>handleCronSetting(cron, record)" />
      </template>
      <template #executeCount="{ text, record }">
        <a @click="handleTask(record)">{{record.running || 0}}/{{record.executeCount || 0}}</a>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getActions(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <NoticeModal @register="registerNoticeModal" @success="reload"/>
    <GroupModal @register="registerGroupModal" @success="reload"/>
    <DesignModal @register="registerDesignModal" @success="reload" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useRouter } from 'vue-router';
  import { list, removeRequest, runRequest, cronRequest, startRequest, stopRequest } from './design.api';
  import { columns, searchFormSchema } from './design.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { propTypes } from '/@/utils/propTypes';
  import { useModal } from '/@/components/Modal';
  import EasyCronLabel from '/@/components/Form/src/jeecg/components/JEasyCron/EasyCronLabel.vue';
  import NoticeModal from './components/noticeModal.vue';
  import GroupModal from './components/groupModal.vue';
  import DesignModal from './DesignModal.vue';

  const { createMessage } = useMessage();
  const { hasPermission } = usePermission();
  const router = useRouter();
  const [registerNoticeModal, { openModal: openNoticeModal }] = useModal();
  const [registerGroupModal, { openModal: openGroupModal }] = useModal();
  const [registerDesignModal, { openModal: openDesignModel }] = useModal();
  
  // 列表页面公共参数、方法
  const { tableContext } = useListPage({
    designScope: 'rpa-design-template',
    tableProps: {
      title: '设计列表',
      api: list,
      columns: columns,
      showIndexColumn: true,
      formConfig: {
        schemas: searchFormSchema,
      },
    },
  });

  const [registerTable, { reload }] = tableContext;

  /**
   * 操作列定义
   * @param record
   */
  function getActions(record) {
    return [
      {
        label: '启动',
        popConfirm: {
          title: '是否启动选中任务？',
          confirm: handlerResume.bind(null, record),
        },
        ifShow: (_action) => {
          return record.enabled == 0 && hasPermission('rpa:flow:resume');
        },
      },
      {
        label: '停止',
        popConfirm: {
          title: '是否暂停选中任务？',
          confirm: handlerPause.bind(null, record),
        },
        ifShow: (_action) => {
          return record.enabled == 1 && hasPermission('rpa:flow:pause');
        },
      },
      {
        label: '手动运行',
        popConfirm: {
          title: '是否立即执行一次？',
          confirm: record.enabled == 0 && handleRun.bind(null, record),
        },
      },
    ];
  }

  /**
   * 更多
   * @param record
   */
  function getDropDownAction(record) {
    return [
      {
        label: '编辑流程',
        onClick: handleEdit.bind(null, record),
        ifShow: (_action) => {
          return record.enabled == 0 && hasPermission('rpa:flow:edit');
        },
      },
      {
        label: '通知设置',
        onClick: handleNotifyOpen.bind(null, record),
        ifShow: (_action) => {
          return record.enabled == 0 && hasPermission('rpa:flow:notify');
        },
      },
      {
        label: '分组设置',
        onClick: handleGroup.bind(null, record),
        ifShow: (_action) => {
          return record.enabled == 0 && hasPermission('rpa:flow:notify');
        },
      },
      {
        label: '执行日志',
        onClick: handleLog.bind(null, record),
      },
      {
        label: '编码复制',
        onClick: handleCopyId.bind(null, record),
      },
      {
        label: '删除流程',
        popConfirm: {
          title: '是否确认删除？',
          confirm: handleDelete.bind(null, record),
          ifShow: (_action) => {
          return record.enabled == 0 && hasPermission('rpa:flow:delete');
        },
        },
      },
    ];
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    openDesignModel(true, {
      isUpdate: false,
    });
  }

  /**
   * 编辑事件
   */
  function handleEdit(record) {
    openDesignModel(true, {
      isUpdate: true,
      record,
    });
  }

  /**
  * 启动定时任务事件
  */
  async function handlerResume(record) {
    await startRequest({id: record.id}, reload);
  }

  /**
   * 暂停定时傻事件
   */
   async function handlerPause(record) {
    await stopRequest({id: record.id}, reload);
  }
  
  /**
   * 手动运行
   */
   async function handleRun(record) {
    await runRequest({ id: record.id }, reload);
  }

  /**
   * 通知设置
   */
  function handleNotifyOpen(record) {
    openNoticeModal(true, {id: record.id});
  }

  /**
   * 分组设置
   * @param record 
   */
  function handleGroup(record){
    openGroupModal(true, {id: record.id, systemId: record.systemId});
  }

  /**
   * 执行日志
   */
  function handleLog(record){
    router.push({
      path: '/rpa/task/detail',
      query: {
        flowId: record.id,
      },
    });
  }

  /**
   * 周期表达式设置
   */
  async function handleCronSetting(cron, record) {
    let params = {
      id: record.id,
      cron: cron,
    };
    await cronRequest(params, reload);
  }
  
  /**
   * 编码复制
   */
  function handleCopyId(record) {
    const cInput = document.createElement('input');
    cInput.value = record.id;
    document.body.appendChild(cInput);
    cInput.select(); // 选取文本框内容
    try {
      var copyed = document.execCommand('copy');
      if (copyed) {
        document.body.removeChild(cInput);
        createMessage.success(`${record.id}复制成功`);
      }
    } catch {
      createMessage.error('复制失败');
    }
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await removeRequest({ id: record.id }, reload);
  }

  /**
   * 运行任务
   */
  function handleTask(record){
    router.push({
      path: '/rpa/task',
      query: {
        flowId: record.id,
        flowName: record.name
      },
    });
  }
  
</script>
